'use strict';

const Controller = require('egg').Controller;
const crypto = require('crypto');

class UsersController extends Controller {
  // 用户列表
  async index() {
    const { ctx, service } = this;
    const { page, page_size } = ctx.request.query;
    const rules = {
      page: { type: 'number', min: 1 },
      page_size: { type: 'number', min: 1 },
    };
    ctx.validate(rules, ctx.request.query);
    const ret = await service.users.findAndCountAll({ page: Number(page), page_size: Number(page_size) });
    ctx.helper.res_success(ret);
  }

  async new() {
    const { ctx } = this;
    console.log(ctx.request.url, 'new');
  }

  // 用户详情
  async show() {
    const { ctx, service } = this;
    const User = await service.users.findOne({ where: { id: ctx.params.id } });
    ctx.helper.res_success(User);
  }

  async edit() {
    const { ctx } = this;
    console.log(ctx.request.url, 'edit');
  }

  async create() {
    const { ctx } = this;
    console.log(ctx.request.url, 'create');
  }

  async update() {
    const { ctx } = this;
    console.log(ctx.request.url, 'update');
  }

  async destroy() {
    const { ctx } = this;
    console.log(ctx.request.urlt, 'destory');
  }

  // 登录
  async login() {
    const { ctx, service } = this;
    const { username, password } = ctx.request.body;

    const User = await service.users.findOne({ where: { tel: username, password: crypto.createHash('md5').update(password).digest('hex') } });
    if (User) {
      const { id, nickname, avatar, tel, create_time, update_time } = User.toJSON();
      // ctx.state = data.token;
      ctx.helper.res_success(
        {
          id,
          nickname,
          avatar,
          tel,
          create_time,
          update_time,
          token: ctx.helper.getToken({ id, nickname, avatar }),
        }
      );
    } else {
      ctx.helper.res_fail(false, '账号密码错误！');
    }
  }

  // 注册
  async register() {
    const { ctx, service } = this;
    const { username, nickname, sex, avatar, age, tel, password } = ctx.request.body;
    const rules = {
      username: { type: 'string', required: true },
      nickname: { type: 'string', required: true },
      sex: { type: 'enum', values: [ 'male', 'female', 'unknown' ], required: true },
      avatar: { type: 'string', required: true },
      age: { type: 'integer', min: 0, max: 200, required: true, msg: '请输入年龄' },
      tel: { type: 'mobile', required: true },
      password: { type: 'pwd', required: true, allowEmpty: false, min: 6 },
    };
    ctx.validate(rules, ctx.request.body);
    const User = await service.users.findOne({ where: { tel } }); // 防止用户重复
    if (User) {
      ctx.helper.res_fail(false, '账号已注册');
      return;
    }
    const ret = await service.users.create({ username, nickname, sex, avatar, age, tel, password });
    ctx.helper.res_success(ret);
  }
}

module.exports = UsersController;
